<?php 
	/**
	 * 
	 传递的参数
		1长度
		2.宽度
		3.字符的数量
	 功能	
		1.创建画布
		2.填充画布颜色
		3.填写干扰元素
		4.获取字符
		5.写入字符
		6.输出图片
	 */

	class Vcode {
		//成员属性
		public $width;//长度
		public $height;//高度
		public $num;//数量
		public $res;//验证码图片的资源
		public $codes = "";//当前要写入图像的字符串


		//构造方法
		public function __construct($width,$height,$num){
			$this->width = $width;
			$this->height = $height;
			$this->num = $num;
		}

		//产生验证码的方法
		public function createVcode(){
			//1创建画布
			$this->createRes();
			//2填充画布颜色
			$this->fill();
			//3添加干扰元素
			$this->createDis();
			//4获取验证码字符
			$this->getCodes();
			//5 将字符串写入画布
			$this->writeCodes();
			//6.输出图片
			$this->outPut();

		}

		private function outPut(){
			header('content-type:image/png');
			imagepng($this->res);
		}

		//写入 imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
		private function writeCodes(){
			for($i=0;$i<$this->num;$i++){
				$size = 16;
				$angle = rand(-10, 10);
				$x = $i*($this->width/$this->num)+($this->width/$this->num)/2;
				$y = 30;
				$color = imagecolorallocate($this->res, rand(0,126), rand(0,126), rand(0,126));
				$fontfile = "./msyh.ttf";
				$text = $this->codes{$i};

				//开始写入
				imagettftext($this->res, $size, $angle, $x, $y, $color, $fontfile, $text);
			}
		}

		//获取字符
		private function getCodes(){
			//所有字符
			$allChars = "3456789qwertyuipasdfghjkxcvbnm";
			//

			for($i=0;$i<$this->num;$i++){
				//获取随机数
				$len = strlen($allChars);
				$r = rand(0,$len-1);
				$this->codes .= $allChars{$r};
			}
			//将字符串写入session
			session_start();
			$_SESSION['vcode'] = $this->codes;
		}

		//创建干扰元素
		private function createDis(){
			//创建点干扰元素   bool imagesetpixel ( resource $image , int $x , int $y , int $color )
			for($i=0;$i<20;$i++){
				$x = rand(0, $this->width);
				$y = rand(0, $this->height);
				$color = imagecolorallocate($this->res, rand(0,255), rand(0,255),rand(0,255));
				imagesetpixel($this->res, $x, $y, $color);
			}

			//创建线的干扰元素  bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
			for($i=0;$i<10;$i++){
				//起始点的坐标
				$x1 = rand(0,$this->width);
				$y1 = rand(0,$this->height);
				//终点的坐标
				$x2 = rand(0,$this->width);
				$y2 = rand(0,$this->height);
				//线段的颜色
				$color = imagecolorallocate($this->res, rand(125,255),rand(125,255),rand(125,255));

				imageline($this->res, $x1, $y1, $x2, $y2, $color);
			}
		}

		//填充颜色
		private function fill(){
			//获取颜色的随机数
			$red = rand(0,255);
			$green = rand(0,255);
			$blue = rand(0,255);
			//创建颜色资源
			$color = imagecolorallocate($this->res, $red, $green, $blue);
			//填充画布
			imagefill($this->res, 0, 0, $color);
		}

		//创建画布资源 方法
		private function createRes(){
			$this->res = imagecreatetruecolor($this->width, $this->height);
		}	

	}

	$img = new Vcode(200, 40, 4);
	$img->createVcode();


 ?>